package cn.wolfcode.edu.web.controller;

import cn.wolfcode.edu.domain.HanCloud;
import cn.wolfcode.edu.service.IHanCloudService;
import cn.wolfcode.edu.util.JsonResult;
import cn.wolfcode.edu.util.UploadUtil;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

@Controller
@RequestMapping("hancloud")
public class HanCloudController {

    @Autowired
    private IHanCloudService hanCloudService;
    @Autowired
    private ServletContext context;

    //定位到云盘界面
    @RequestMapping("")
    public String goToHanCloud(){
        return "cloud/hanCloud";
    }

    //查询指定用户对象拥有的目录
    @RequestMapping("queryMenusByEmployeeId")
    @ResponseBody
    public List<HanCloud> queryMenusByEmployeeId(){
        return hanCloudService.queryMenusByEmployeeId();
    }

    //新增者文件夹
    @RequestMapping("save")
    @ResponseBody
    public JsonResult save(HanCloud hanCloud){
        hanCloudService.save(hanCloud);
        return new JsonResult();
    }

    //文件上传
    @RequestMapping("upload")
    @ResponseBody
    public JsonResult upload(MultipartFile file,Long parentId,String fileName){
        String dir = context.getRealPath("/upload");
        String path = UploadUtil.upload(file, dir);
        hanCloudService.upload(path,parentId,fileName);
        return new JsonResult();
    }

    //文件下载
    @RequestMapping("download")
    public void download(String filename,String path, HttpServletResponse resp) throws Exception{
        //设置下载响应头
        resp.setContentType("application/x-msdownload");
        resp.setHeader("Content-Disposition", "attachment;filename="+filename);

        int index = path.lastIndexOf("/");
        String uuidName = path.substring(index + 1);
        String div = context.getRealPath("/upload");
        Files.copy(Paths.get(div,uuidName),resp.getOutputStream());

    }

    //文件删除
    @RequestMapping("delete")
    @ResponseBody
    public JsonResult delete(Long id,String filePath){
        int index = filePath.indexOf("=");
        filePath = filePath.substring(index + 1);
        //删除文件
        UploadUtil.deleteFile(context,filePath);
        hanCloudService.deleteFileById(id);
        return new JsonResult();
    }


}
